package com.hotel.BL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.EntityName;
import com.Util;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;

import data.POSCalTax;
import data.POSCancelReservation;import data.POSGuest;
import data.POSGuestTable;
import data.POSOrder;
import data.POSItem;
import data.POSTax;
import data.POSorderItem;
import data.passingData.POSEditOrderItem;
import data.passingData.POSGuestTableData;

public class POSgenerateOrderLogic extends AbstractBL {
	
	private HttpSession session;

	public POSgenerateOrderLogic(HttpServletRequest req,HttpServletResponse resp){
		this.session = req.getSession(true);
		this.req = req;
		this.resp = resp;
	}
	
	public POSGuestTable AddGuestTable(String table) throws EntityNotFoundException{
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		POSGuestTable t = new POSGuestTable();
		GenericLogic gLogic = new GenericLogic(req,resp);
		t.setTableString(table);
		t.setArrive(gLogic.ServerDateTime());
		t.setNightAuditDate(gLogic.ServerDateFromNightAudit());
		t.setGuestStatus("W");
		t.setHotelId(hotelId);
		
		POSHistoryLogic posHistory = new POSHistoryLogic(req,resp);
		t = posHistory.CreatePOSTable(t);
		
		Key k = datastore.put(t.getEntity());
		t.setId(k.getId());
		t.setKey(k);
		return t;
	}
	
	public POSGuestTableData AddGuestTable(String Name,String timeArrive,String tel,String guestAmount,String table,String note) throws EntityNotFoundException, ParseException{
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm",
				Locale.ENGLISH);
		
		POSGuestTable t = new POSGuestTable();
		POSGuestTableData pd = new POSGuestTableData();
		POSGuest g = new POSGuest();
			g.setName(Name);
			g.setPhoneNumber(tel);
			Key kg = datastore.put(g.getEntity());
			g.setId(kg.getId());
			g.setKey(kg);
			if(g.getId()!=0){
				t.setGuestStatus("R");
			}else{
				t.setGuestStatus("W");
			}
		t.setGuest(g);
		t.setArrive(formatter.parse(timeArrive));
		t.setTableString(table);
		t.setGuestAmount(guestAmount);
		t.setNote(note);
		t.setHotelId(hotelId);
		
		POSHistoryLogic posHistory = new POSHistoryLogic(req,resp);
		t = posHistory.ReservePOSTable(t);
		
		Key k = datastore.put(t.getEntity());
		t.setId(k.getId());
		t.setKey(k);
		if(t.getId()!=0){
			pd.setId(t.getId());
			pd.setName(Name);
			pd.setStatus(t.getGuestStatus());
			pd.setArrivel(t.getArrive());
			pd.setTableId(t.getTableString());
			pd.setTel(tel);
			pd.setNote(t.getNote());
			pd.setGuest(t.getGuestAmount());	
			double money =0;
			if(t.getPOSorderList() != null){
				for(POSOrder d:t.getPOSorderList()){
					for(POSorderItem i:d.getItem()){
						money+=i.getPrice();
					}
				}
			}
			pd.setMoney(money);
			if(t.getPOSorderListString()!=null){pd.setHaveOrder(true);}else{pd.setHaveOrder(false);}
		}
		return pd;
	}
	
	public POSGuestTableData EditGuestTable(String Name,String timeArrive,String tel,String guestAmount,String note,String resId) throws EntityNotFoundException, ParseException{
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm",
				Locale.ENGLISH);
		POSGuestTable t = GetPOSGuestTable(Long.parseLong(resId));
		POSGuestTableData pd = new POSGuestTableData();
		POSGuest g = new POSGuest();
			g.setName(Name);
			g.setPhoneNumber(tel);
			Key kg = datastore.put(g.getEntity());
			g.setId(kg.getId());
			g.setKey(kg);
		t.setGuest(g);
		t.setArrive(formatter.parse(timeArrive));
		t.setGuestAmount(guestAmount);
		t.setNote(note);
		Key k = datastore.put(t.getEntity());
		t.setId(k.getId());
		t.setKey(k);
		if(t.getId()!=0){
			pd.setId(t.getId());
			pd.setName(Name);
			pd.setStatus(t.getGuestStatus());
			pd.setArrivel(t.getArrive());
			pd.setTableId(t.getTableString());
			pd.setTel(tel);
			pd.setNote(t.getNote());
			pd.setGuest(t.getGuestAmount());
			double money =0;
			if(t.getPOSorderList() != null){
				for(POSOrder d:t.getPOSorderList()){
					for(POSorderItem i:d.getItem()){
						money+=i.getPrice();
					}
				}
			}
			pd.setMoney(money);
			if(t.getPOSorderListString()!=null){pd.setHaveOrder(true);}else{pd.setHaveOrder(false);}
		}
		return pd;
	}
	
	public HashMap<String,Object> AddPOSorder(String orderListString,String tableId,String PresId) throws JSONException, EntityNotFoundException{
		POSGuestTable table;long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		HashMap<String,Object> hash = new HashMap<String,Object>();
		if(PresId==null || PresId.equals("null") || PresId==""){
			table = AddGuestTable(tableId);
			hash.put("Arrivel", table.getArrive());
			hash.put("PGuestId", table.getId());
			hash.put("TableId", table.getTableString());
			hash.put("Status", table.getGuestStatus());
		}
		else
			table = GetPOSGuestTable(Long.parseLong(PresId));
		table.setGuestStatus("W");
		Key tk = datastore.put(table.getEntity());
		table.setId(tk.getId());
		table.setKey(tk);
		
		List<POSorderItem> list = AddPOSorderItem(orderListString,tableId);
		List<POSOrder> orderList = table.getPOSorderList();
		
		POSOrder newOrder = new POSOrder();
		newOrder.setHotelId(hotelId);
		newOrder.setDisplayId(GetMaxFolioDisplayId(hotelId)+1);
		newOrder.setItem(list);
		newOrder.setStatus(true);
		Key k = datastore.put(newOrder.getEntity());
		newOrder.setId(k.getId());
		newOrder.setKey(k);
		
		if(orderList == null) orderList = new ArrayList<POSOrder>();
		orderList.add(newOrder);
		table.setPOSorderList(orderList);
		
		POSHistoryLogic posHistory = new POSHistoryLogic(req,resp);
		table = posHistory.OrderGuestTable(table);
		
		UpdatePOSGuestTable(table);
		
		List<HashMap<String,Object>> orderListHash = new ArrayList<HashMap<String,Object>>();
		for(POSOrder order: orderList)
			orderListHash.add(getPOSorderHashMap(order));
		double money =0;
		if(table.getPOSorderList() != null){
			for(POSOrder d:table.getPOSorderList()){
				for(POSorderItem i:d.getItem()){
					money+=i.getPrice();
				}
			}
		}
		hash.put("money", money);
		hash.put("OrderList", orderListHash);
		if(table.getPOSorderListString()!=null){hash.put("haveOrder",true);}else{hash.put("haveOrder", false);}
		return hash;
	}
	
	public List<HashMap<String,Object>> GetPOSOrderList(long gtableid) throws JSONException, EntityNotFoundException{
		POSGuestTable table = GetPOSGuestTable(gtableid);
		List<POSOrder> orderList = table.getPOSorderList();
		
		List<HashMap<String,Object>> orderListHash = new ArrayList<HashMap<String,Object>>();
		for(POSOrder order: orderList)
			orderListHash.add(getPOSorderHashMap(order));
		return orderListHash;
	}
	
	private HashMap<String,Object> getPOSorderHashMap(POSOrder order){
		HashMap<String,Object> tmpOrder = new HashMap<String,Object>();
		tmpOrder.put("id", order.getId());
		tmpOrder.put("displayId", order.getDisplayId());
		tmpOrder.put("status", order.isStatus());
		List<POSorderItem> listItem = order.getReloadItem();
		List<HashMap<String,Object>> listItemHash = new ArrayList<HashMap<String,Object>>();
		for(POSorderItem item : listItem)
			listItemHash.add(getPOSorderItemHashMap(item));
		tmpOrder.put("items", listItemHash);
		return tmpOrder;
	}
	
	private HashMap<String,Object> getPOSorderItemHashMap(POSorderItem item){
		HashMap<String,Object> tmpItem = Util.toHashmap(item);
		tmpItem.remove("tax");
		List<POSCalTax> taxCal = item.getReloadTax();
		List<HashMap<String,Object>> taxList = new ArrayList<HashMap<String,Object>>();
		if(taxCal!=null)
			for(POSCalTax tax: taxCal){
				HashMap<String,Object> tmp = Util.toHashmapformfield(tax);
				taxList.add(tmp);
			}
		tmpItem.put("tax", taxList);
		return tmpItem;
	}
	
	public POSGuestTable UpdatePOSGuestTable(POSGuestTable posG)
	{
		Key key = datastore.put(posG.getEntity());
		posG.setId(key.getId());
		posG.setKey(key);
		return posG;
	}

	public List<POSorderItem> AddPOSorderItem(String orderList,String tableId) throws JSONException, EntityNotFoundException{
			JSONArray jsonArray = new JSONArray(orderList);
			JSONObject jo = new JSONObject();
			List<POSorderItem> list = new ArrayList<POSorderItem>();
		    jo.put("arrayName",jsonArray);
		    JSONArray j = jo.getJSONArray("arrayName");
		    POSItemLogic posItemLogic = new POSItemLogic(req,resp);
		    for (int i = 0; i < j.length(); i++) {
		    	POSItem item = posItemLogic.GetPOSItem(Long.parseLong(j.getJSONObject(i).get("id").toString()));
		    	List<HashMap<String,Object>> taxList = posItemLogic.CalEachTax(item.getPrice(),item.getTax(),0,1,session);
		    	POSorderItem t = new POSorderItem();
		    	t.setItemString(String.valueOf(item.getId()));
		    	t.setCancel(false);
		    	t.setDiscount(0);
		    	t.setAmount(Long.parseLong(j.getJSONObject(i).get("q").toString()));
		    	t.setPrice(item.getPrice());
		    	t.setStatus(true);
		    	t.setTitle(item.getTitle());
		    	List<POSCalTax> listPOSCalTax = new ArrayList<POSCalTax>();
		    	if(taxList!=null)
			    	for(HashMap<String,Object> hash : taxList){
			    		POSCalTax calTaxItem = CreatePOSCalTax((Long)hash.get("POSTaxId"),(Double)hash.get("Value"));
			    		listPOSCalTax.add(calTaxItem);
			    	}
		    	t.setTax(listPOSCalTax);
		    	Key k = datastore.put(t.getEntity());
		    	t.setId(k.getId());
				t.setKey(k);
				
				list.add(t);
		    }
			return list;
	}
	
	public POSCalTax CreatePOSCalTax(long taxId,double value) throws EntityNotFoundException{
		POSCalTax t = new POSCalTax();
		t.setTaxValue(value);
		t.setTaxString(Long.toString(taxId));
		Key k = datastore.put(t.getEntity());
		t.setId(k.getId());
		t.setKey(k);
		return t;
	}
	
	public List<POSGuestTable> GetPOSGuestTableAll(Date dateTo,Date dateForm) {
		Query q = new Query(EntityName.POSGuestTable);
		Filter lessDate= new FilterPredicate("arrive",
				FilterOperator.LESS_THAN, dateTo);
		Filter morDate = new FilterPredicate("arrive",
				FilterOperator.GREATER_THAN_OR_EQUAL, dateForm);
		Filter close= new FilterPredicate("isClosed",
				FilterOperator.EQUAL, false);
		Filter status= new FilterPredicate("status",
				FilterOperator.EQUAL, true);
		Filter filter = CompositeFilterOperator.and(lessDate,
				morDate,close,status);
		q.setFilter(filter);
		return GetList(datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()));
	}
	
	public List<POSGuestTable> GetList(List<Entity> entities) {
		List<POSGuestTable> list = new ArrayList<POSGuestTable>();
		if(entities!=null)
			for (Entity e : entities) {
				POSGuestTable a = new POSGuestTable();
				a.setEntity(e);
				list.add(a);
			}
		return list;
	}
	public List<POSorderItem> GetOrderItemList(List<Entity> entities) {
		List<POSorderItem> list = new ArrayList<POSorderItem>();
		if(entities!=null)
			for (Entity e : entities) {
				POSorderItem a = new POSorderItem();
				a.setEntity(e);
				list.add(a);
			}
		return list;
	}
	public List<POSOrder> GetOrderList(List<Entity> entities) {
		List<POSOrder> list = new ArrayList<POSOrder>();
		if(entities!=null)
			for (Entity e : entities) {
				POSOrder a = new POSOrder();
				a.setEntity(e);
				list.add(a);
			}
		return list;
	}
	
	public POSGuestTable GetPOSGuestTable(long id) {
		Key key = KeyFactory.createKey(EntityName.POSGuestTable, id);
		try {
			Entity lang = datastore.get(key);
			POSGuestTable c = new POSGuestTable();
			c.setEntity(lang);
			return c;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
	
	public POSOrder GetPOSOrder(long id) {
		Key key = KeyFactory.createKey(EntityName.POSOrder, id);
		try {
			Entity lang = datastore.get(key);
			POSOrder c = new POSOrder();
			c.setEntity(lang);
			return c;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
	
	public POSorderItem GetPOSOrderItem(long id) {
		Key key = KeyFactory.createKey(EntityName.POSorderItem, id);
		try {
			Entity lang = datastore.get(key);
			POSorderItem c = new POSorderItem();
			c.setEntity(lang);
			return c;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
	
	public POSCalTax GetPOSCalTax(long id) {
		Key key = KeyFactory.createKey(EntityName.POSCalTax, id);
		try {
			Entity lang = datastore.get(key);
			POSCalTax c = new POSCalTax();
			c.setEntity(lang);
			return c;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
	
	public POSOrder UpdatePOSOrder(POSOrder o)
	{
		Key key = datastore.put(o.getEntity());
		o.setId(key.getId());
		o.setKey(key);
		return o;
	}	
	public POSorderItem UpdatePOSOrderItem(POSorderItem o)
	{
		Key key = datastore.put(o.getEntity());
		o.setId(key.getId());
		o.setKey(key);
		return o;
	}
	public POSCalTax UpdatePOSCalTax(POSCalTax o)
	{
		Key key = datastore.put(o.getEntity());
		o.setId(key.getId());
		o.setKey(key);
		return o;
	}

	/*@SuppressWarnings("unchecked")
	public HashMap<String,Object> AddEditOrderItemAmount(long gtableId,long itemId, long amount) throws EntityNotFoundException {
		POSorderItem orderItem = GetPOSOrderItem(itemId);
		orderItem.setAmount(amount);
		List<POSCalTax> posCalTax = orderItem.getTax();
		
		POSItemLogic posItemLogic = new POSItemLogic(req,resp);
		POSItem item = posItemLogic.GetPOSItem(Long.parseLong(orderItem.getItemString()));
		HashMap<String,Object> calTax = posItemLogic.CalTaxEachItem(orderItem.getPrice() - (orderItem.getDiscount()/orderItem.getAmount()),item.getTax(),session);
		List<HashMap<String,Object>> taxList = (List<HashMap<String, Object>>) calTax.get("Tax");
    	
		if(taxList!=null)
		for(HashMap<String,Object> taxItem : taxList)
			for(POSCalTax posCalTaxItem:posCalTax)
				if(posCalTaxItem.getTaxString().equals(Long.toString((Long)taxItem.get("POSTaxId"))))
				{
					posCalTaxItem.setTaxValue((Double)taxItem.get("Value"));
					UpdatePOSCalTax(posCalTaxItem);
				}
		orderItem.getTax_Reload();
		
		POSGuestTable table = GetPOSGuestTable(gtableId);
		POSHistoryLogic posHistory = new POSHistoryLogic(req,resp);
		table = posHistory.OrderEditAmountItem(table);
		UpdatePOSGuestTable(table);
		
		POSorderItem rs = UpdatePOSOrderItem(orderItem);
		return getPOSorderItemHashMap(rs);
	}

	@SuppressWarnings("unchecked")
	public HashMap<String,Object> AddEditOrderItemDiscount(long gtableId,long itemId, double discount,HttpSession session) throws EntityNotFoundException {
		POSorderItem orderItem = GetPOSOrderItem(itemId);
		orderItem.setDiscount(discount);
		
		List<POSCalTax> posCalTax = orderItem.getTax();
		
		POSItemLogic posItemLogic = new POSItemLogic(req,resp);
		POSItem item = posItemLogic.GetPOSItem(Long.parseLong(orderItem.getItemString()));
		
		boolean isIncludeTax = (Boolean)session.getAttribute("isIncludetax");
		double itemPrice = orderItem.getPrice();
		if(isIncludeTax){
			List<HashMap<String,Object>> calTax = (List<HashMap<String, Object>>) posItemLogic.CalTaxEachItem(itemPrice,item.getTax(),false).get("Tax");
			double totalTax = 0;
			if(calTax!=null)
			for(HashMap<String,Object> t : calTax)
				totalTax += (Double)t.get("Value");
			itemPrice = (orderItem.getPrice() + totalTax) - (orderItem.getDiscount()/orderItem.getAmount());
		}
		else itemPrice = orderItem.getPrice() - (discount/orderItem.getAmount());
		HashMap<String,Object> calTax = posItemLogic.CalTaxEachItem(itemPrice,item.getTax(),isIncludeTax);
		List<HashMap<String,Object>> taxList = (List<HashMap<String, Object>>) calTax.get("Tax");
    	
		if(taxList!=null)
		for(HashMap<String,Object> taxItem : taxList)
			for(POSCalTax posCalTaxItem:posCalTax)
				if(posCalTaxItem.getTaxString().equals(Long.toString((Long)taxItem.get("POSTaxId"))))
				{
					posCalTaxItem.setTaxValue((Double)taxItem.get("Value"));
					UpdatePOSCalTax(posCalTaxItem);
				}
		orderItem.getTax_Reload();

		POSGuestTable table = GetPOSGuestTable(gtableId);
		POSHistoryLogic posHistory = new POSHistoryLogic(req,resp);
		table = posHistory.OrderEditDiscountItem(table);
		UpdatePOSGuestTable(table);
		
		POSorderItem rs = UpdatePOSOrderItem(orderItem);
		return getPOSorderItemHashMap(rs);
	}*/
	
	public long CancelPOSReservation(long hotelId,long pOSresId,String reason,String detail) throws EntityNotFoundException {
		boolean status =AddPOSReasonCancelation(hotelId,pOSresId,reason,detail);
		if(status){
			POSGuestTable r = GetPOSGuestTable(pOSresId);
			r.setStatus(false);
			Key k = datastore.put(r.getEntity());
			r.setId(k.getId());
			r.setKey(k);
			return pOSresId;
		}
	return 0;
	}
	
	public boolean AddPOSReasonCancelation(long hotelId,long pOSresId,String reason,String detail) throws EntityNotFoundException {
		POSCancelReservation c = new POSCancelReservation();
		c.setHotelId(hotelId);
		c.setPOSresId(pOSresId);
		c.setReason(reason);
		c.setDetail(detail);
		c.setAvaliable(true);
		c.setStatus(true);
		Key k = datastore.put(c.getEntity());
		c.setId(k.getId());
		c.setKey(k);
		if(c.getId()!=0){
			return true;
		}else{
			return false;
		}
		
	}
	
	public POSGuestTable AddNote(long posresId,String title) throws EntityNotFoundException{
		POSGuestTable table = GetPOSGuestTable(posresId);
		
		POSHistoryLogic posHistory = new POSHistoryLogic(req,resp);
		table = posHistory.AddNote(table, title);
		
		return table;
	}
	public long GetMaxOrderDisplayId(long hotelId)
	{
		Query q = new Query(EntityName.POSOrder);

		Filter filterHotel = new FilterPredicate("hotelId", FilterOperator.EQUAL, hotelId);
		q.setFilter(filterHotel).addSort("displayId", SortDirection.DESCENDING);

		List<POSOrder> list = GetOrderList(datastore.prepare(q).asList(FetchOptions.Builder.withLimit(1)));
		if(list.size()>0)
			return list.get(0).getDisplayId();
		return 0;
	}
	public long GetMaxFolioDisplayId(long hotelId)
	{
		Query q = new Query(EntityName.POSGuestTable);

		Filter filterHotel = new FilterPredicate("hotelId", FilterOperator.EQUAL, hotelId);
		q.setFilter(filterHotel).addSort("displayFolioId", SortDirection.DESCENDING);

		List<POSGuestTable> list = GetList(datastore.prepare(q).asList(FetchOptions.Builder.withLimit(1)));
		long displayOrderId = GetMaxOrderDisplayId(hotelId);
		if(list.size()>0){
			long displayFolio =  list.get(0).getDisplayFolioId();
			return (displayFolio>displayOrderId)? displayFolio : displayOrderId;
		}
		else return displayOrderId;
	}

	public HashMap<String, Object> EditOrderItem(long posOrderId,List<POSEditOrderItem> itemList) throws Exception {
		POSOrder order = GetPOSOrder(posOrderId);
		if(itemList!=null){
			List<POSorderItem> orderItems = new ArrayList<POSorderItem>();
			POSItemLogic posItemLogic = new POSItemLogic(req,resp);
			POSTaxLogic posTaxLogic = new POSTaxLogic(req,resp);
			for(POSEditOrderItem tmpItem:itemList){
				List<Long> taxIdList = tmpItem.getTaxList();
				List<POSTax> posTaxList = new ArrayList<POSTax>();
				if(taxIdList!=null)
					for(Long _id:taxIdList)
						posTaxList.add(posTaxLogic.GetPOSTax(_id));
				if(tmpItem.getId() > 0){
					POSorderItem item = GetPOSOrderItem(tmpItem.getId());
					if(tmpItem.isS()){
						item.setAmount(tmpItem.getA());
						item.setDiscount(tmpItem.getDiscount());
						if(posTaxList.size()>0)
							item = UpdatePOSCalTax(item,posTaxList);
						else
							item = UpdatePOSCalTax(item);
						UpdatePOSOrderItem(item);
						orderItems.add(item);
					}
					else{
						List<POSCalTax> caltax = item.getTax();
						if(caltax!=null)
							for(POSCalTax tax:caltax)
								datastore.delete(tax.getEntity().getKey());
						datastore.delete(item.getEntity().getKey());
					}
				}else if(tmpItem.getItem()!=null&&tmpItem.getItem()!=""){
					POSItem positem = posItemLogic.GetPOSItem(Long.parseLong(tmpItem.getItem()));
					POSorderItem item = new POSorderItem();
					item.setItemString(String.valueOf(tmpItem.getItem()));
					item.setCancel(false);
					item.setDiscount(tmpItem.getDiscount());
					item.setAmount(tmpItem.getA());
			    	item.setPrice(positem.getPrice());
			    	item.setStatus(true);
			    	item.setTitle(positem.getTitle());
			    	item.setItem(positem);
			    	Key k = datastore.put(item.getEntity());
			    	item.setId(k.getId());
					item.setKey(k);
					if(posTaxList.size()>0)
						UpdatePOSCalTax(item,posTaxList);
					else
						item = UpdatePOSCalTax(item);
					orderItems.add(item);
				}else{
					POSorderItem item = new POSorderItem();
					item.setCancel(false);
					item.setDiscount(tmpItem.getDiscount());
					item.setAmount(tmpItem.getA());
			    	item.setPrice(tmpItem.getPrice());
			    	item.setStatus(true);
			    	item.setTitle(tmpItem.getTitle());
			    	Key k = datastore.put(item.getEntity());
			    	item.setId(k.getId());
					item.setKey(k);
					item = UpdatePOSCalTax(item,posTaxList);
					orderItems.add(item);
				}
			}
			if(orderItems.size()>0)
				for(POSorderItem item:orderItems)
					item = UpdatePOSOrderItem(item);
			order.setItem(orderItems);
			order = UpdatePOSOrder(order);
		}
		return getPOSorderHashMap(order);
	}
	
	public POSorderItem UpdatePOSCalTax(POSorderItem item) throws EntityNotFoundException{
		return UpdatePOSCalTax(item,item.getItem().getTax());
	}
	public POSorderItem UpdatePOSCalTax(POSorderItem item,List<POSTax> taxlist) throws EntityNotFoundException{
		List<POSCalTax> avaliableTaxList = item.getTax();
		if(avaliableTaxList!=null)
			for(long i=0;i<avaliableTaxList.size();i++)
				datastore.delete(((POSCalTax)avaliableTaxList.get((int) i)).getEntity().getKey());
		
		avaliableTaxList = new ArrayList<POSCalTax>();
		POSItemLogic posItemLogic = new POSItemLogic(req,resp); 
		List<HashMap<String,Object>> taxList = posItemLogic.CalEachTax(item.getPrice(), taxlist, item.getDiscount(), item.getAmount(), session);
    	for(HashMap<String,Object> hash : taxList){
    		POSCalTax calTaxItem = CreatePOSCalTax((Long)hash.get("POSTaxId"),(Double)hash.get("Value"));
    		avaliableTaxList.add(calTaxItem);
    	}
    	item.setTax(avaliableTaxList);
		return item;
	}

	public POSOrder CancelOrder(long posOrderId) {
		POSOrder order = GetPOSOrder(posOrderId);
		order.setStatus(false);
		order = UpdatePOSOrder(order);
		return order;
	}
}

